<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.partner_delete" @click="handleDelete">删 除</el-button>
      </template>
      <template slot="menu" slot-scope="{ type, size, row }">
        <el-button :size="size" :type="type" @click="associationRules(row.id)" v-if="permission.association_rules">关联规则</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
    </avue-crud>
    <el-dialog
      v-dragDirectives
      ref="dialog"
      :title="dialogTitle"
      append-to-body
      :visible.sync="showRulesDialog"
      :close-on-click-modal="false"
      top="5vh"
      width="70%"
      @close="closeDialog"
    >
      <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>关联规则明细</h3>
      <avue-crud
        :option="rulesInfoOption"
        :table-loading="loading"
        :data="rulesInfoList"
        ref="rulesInfoCrud"
        @row-save="rulesInfoRowSave"
        @row-update="rulesInfoRowUpdate"
        @row-del="rulesInfoRowDel"
        @selection-change="basicInfoSelectionChange"
      >
        <template slot="menuLeft">
          <el-button v-if="dialogTitle != '详情'" type="primary" size="small" @click="addRules">添加规则</el-button>
          <el-button v-if="dialogTitle != '详情'" type="danger" size="small" icon="el-icon-delete" @click="rulesInfoDelete">删 除</el-button>
        </template>
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitRules"><i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
        <el-button size="small" @click="showRulesDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>

<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList, getDetail, remove, addOrUpdate, getActivityRules, addRulesData } from '@/api/flow/activity-management.js';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'FlowActivityManagement',
  components: { CommonModalTemplate, userTableConfig },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'ACTIVITY_MANAGEMENT',
      modalName: '',
      form: {},
      query: {},
      defaults: {},
      timer: new Date().getTime(),
      editDialog: false,
      loading: false,
      data: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        dialogWidth: '35%',
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        labelWidth: 110,
        border: true,
        span: 24,
        index: true,
        indexLabel: '序号',
        addBtn: true,
        editBtn: true,
        delBtn: true,
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '模块',
            prop: 'module',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=sys_module',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择模块',
                trigger: 'change'
              }
            ]
          },
          {
            label: '活动名称',
            prop: 'actName',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入活动类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '活动编码',
            prop: 'actCode',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入活动编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '活动类型',
            prop: 'actType',
            type: 'select',
            search: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=activity_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择活动类型',
                trigger: 'change'
              }
            ]
          },
          {
            label: '编排代码',
            prop: 'chainCode',
            type: 'search',
            appendClick: () => {
              this.openUserCommonModal('chainCodeModel');
            },
            rules: [
              {
                required: true,
                message: '请选择编排代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '适用业务场景',
            prop: 'forBiz',
            type: 'textarea',
            span: 24,
            maxRows: 3,
            minRows: 3,
            rules: [
              {
                required: true,
                message: '请填写适用业务场景',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '启用',
            prop: 'status',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ],
            value: 1
          }
        ]
      },
      showRulesDialog: false,
      rulesInfoOption: {
        height: 500,
        calcHeight: 30,
        tip: false,
        border: true,
        index: false,
        indexLabel: '序号',
        indexWidth: 200,
        addBtn: false,
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        cellBtn: true,
        menuWidth: 200,
        column: [
          {
            label: '规则名称',
            prop: 'name'
          },
          {
            label: '规则编码',
            prop: 'code'
          },
          {
            label: '规则校验顺序',
            prop: 'order',
            cell: true
          }
        ]
      },
      rulesInfoList: [], //关联规则明细数据
      basicInfoSelectionList: [],
      rulesControlsDeleteIds: [],
      tableOption: {} //公用模态框配置信息
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.activityManagement_add, false),
        delBtn: this.vaildData(this.permission.activityManagement_delete, false),
        editBtn: this.vaildData(this.permission.activityManagement_edit, false),
        viewBtn: this.vaildData(this.permission.activityManagement_view, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    basicInfoIndex() {
      let indexs = [];
      this.basicInfoSelectionList.forEach((ele) => {
        indexs.push(ele.$index);
      });
      return indexs;
    }
  },
  methods: {
    /**
     * 关联规则
     * activityId - row.id
     */
    associationRules(activityId) {
      // 1. 先将弹窗开启，默认是有表头的 √  2. 进行选择规则管理中的数据 √  3. 渲染选择好的数据在弹窗列表中 √ 4. 列表的配置是增加开关开启与序号自动排序的
      this.showRulesDialog = true;
      this.dialogTitle = '关联规则';
      this.activityId = activityId;
      getActivityRules(activityId).then((res) => {
        const data = res.data.data.records;
        for (let i = 0; i < data.length; i++) {
          this.rulesInfoList.push({
            $cellEdit: false,
            id: data[i].id,
            rulesId: data[i].checkitemId,
            name: data[i].name,
            code: data[i].code,
            type: data[i].type,
            field: data[i].field,
            order: data[i].order
          });
        }
      });
    },

    /**
     * 添加规则
     */
    addRules() {
      this.modalName = 'rulesModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择规则',
        url: '/api/mes-admin/checkItem/page',
        isPage: true,
        rowSelectionType: 'multiple',
        isDefaultLoad: true,
        columnDefs: [
          {
            label: '规则名称',
            prop: 'name',
            search: true
          },
          {
            label: '规则编码',
            prop: 'code'
          },
          {
            label: '规则类型',
            prop: 'type'
          },
          {
            label: '规则字段',
            prop: 'field'
          }
        ]
      };
    },

    /**
     * 选择模态框行数据
     */
    getSelectedRows(row) {
      switch (this.modalName) {
        case 'rulesModal':
          for (let i = 0; i < row.length; i++) {
            this.rulesInfoList.push({
              $cellEdit: true,
              rulesId: row[i].id,
              name: row[i].name,
              code: row[i].code,
              type: row[i].type,
              field: row[i].field
            });
          }
          break;
        case 'chainCodeModel':
          this.form.chainCode = this._get(row, 'chainCode', '');
          break;
        default:
          break;
      }
    },

    /**
     * 提交保存关联规则
     */
    submitRules() {
      let ids = [];
      this.rulesInfoList.forEach((ele) => {
        ids.push({
          id: ele.id,
          activityId: this.activityId,
          checkitemId: ele.rulesId,
          order: ele.order
        });
      });
      //   let params = {
      //     activityCheckItemList: ids
      //   };
      addRulesData(ids).then(
        (res) => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.showRulesDialog = false;
        },
        (error) => {}
      );
    },

    /**
     * 提交保存
     */
    rowSave(row, done, loading) {
      addOrUpdate(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      addOrUpdate(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(row) {
      if (this.selectionList.length === 0 && !row.id) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    /**
     * 打开avue-crud之前的调用
     */
    // beforeOpen(done, type) {
    //   if (['add', 'edit', 'view'].includes(type)) {
    //     this.defaults.field.type = 'search';
    //   }
    //   done();
    // },
    // beforeClose(done, type) {
    //   this.defaults.field.type = 'input';
    //   done();
    // },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    rulesInfoRowSave(form, done) {
      done();
    },
    rulesInfoRowUpdate(form, index, done) {
      done();
    },
    rulesInfoRowDel(row, index) {
      this.rulesInfoList.splice(index, 1);
      if (row.id) {
        this.rulesControlsDeleteIds.push(row.id);
      }
    },
    basicInfoSelectionChange(list) {
      this.basicInfoSelectionList = list;
    },
    rulesInfoDelete() {
      if (this.basicInfoSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let selectList = [];
        this.rulesControlsDeleteIds = [];
        this._forEach(this.basicInfoIndex, (item) => {
          selectList.push(this.rulesInfoList[item]);
          if (this.rulesInfoList[item].id) {
            this.rulesControlsDeleteIds.push(this.rulesInfoList[item].id);
          }
        });
        this._forEach(selectList, (item) => {
          let index = this.rulesInfoList.indexOf(item);
          this.rulesInfoList.splice(index, 1);
        });
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.$refs.rulesInfoCrud.toggleSelection();
      });
    },

    closeDialog() {
      //   this.$refs.basicInfoForm.resetFields();
      this.form = {};
      this.rulesInfoList = [];
      this.rulesControlsDeleteIds = [];
    },

    openUserCommonModal(params) {
      this.modalName = params;
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择组件流程编排代码',
        url: '/api/mes-admin/chain/page',
        isPage: true, // 显示分页器
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        query: {},
        columnDefs: [
          {
            label: '编排代码',
            prop: 'chainCode',
            search: true
          },
          {
            label: '应用程序名',
            prop: 'applicationName'
          }
        ]
      };
    }
  }
};
</script>

<style></style>
